import webapp2
import jinja2
import os
import json
from datetime import datetime
from google.appengine.api import channel
from google.appengine.api import users

class Page(webapp2.RequestHandler):
  values = {}
  
  def get(self, *paths):
    user = users.get_current_user()
    if user:
      token = channel.create_channel("%s" % user.email())
      self.values['token'] = token
      self.values['identifier'] = "%s" % datetime.now()

      jinja_environment = jinja2.Environment(
      loader=jinja2.FileSystemLoader(os.path.dirname(__file__) +'/'))
      tpl = 'index'
      if len(paths) > 0 and paths[0] == 'control':
        tpl = 'control'
      template = jinja_environment.get_template('%s.html' % tpl)

      self.response.out.write(template.render(self.values))
    else:
      self.redirect(users.create_login_url(self.request.uri))

  def post(self, *paths):
    user = users.get_current_user()
    if user:
      key = self.request.get('key')

      message = json.dumps({'key': key})
      result = channel.send_message("%s" % user.email(), message)

app = webapp2.WSGIApplication([('/(.*)', Page)], debug=True)
